<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 页面基础控制器
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: controller.php 213 2012-05-24 09:33:22Z yellow.chow $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
abstract class Controller extends Kohana_Controller
{

    /**
     * @var View
     */
    public $view = NULL;

    /**
     * @var bool
     **/
    public $auto_render = TRUE;

    /**
     * @var string
     */
    public $template = NULL;

    /**
     * Loads the [View] object.
     */
    public function before()
    {
        // Set the global view variables
        View::set_global('directory',  Request::$initial->directory());
        View::set_global('controller', Request::$initial->controller());
        View::set_global('action',     Request::$initial->action());

        if ($this->auto_render === TRUE)
        {
            // Load the view
            $this->view = new View;
        }

        // Template file for View
        $this->template = $this->request->directory().DS.str_replace('_',DS,$this->request->controller()).DS.$this->request->action();
    }

    /**
     * Assigns the [View] as the request response.
     */
    public function after()
    {
        if ($this->auto_render === TRUE)
        {
            try
            {
                $this->view->set_filename($this->template);
            }
            catch(Exception $e)
            {
                die("Template file '{$this->template}' is not exist!");
            }

            if ( ! headers_sent())
            {
                @header("Content-type: text/html; charset=utf-8");
            }

            $this->response->body($this->view->render());
        }
    }

    /**
     * 渲染视图并输出
     *
     * @param  string  $file
     */
    public function render($file = NULL)
    {
        $this->auto_render = FALSE;
        $this->response->body($this->view->render($file));
    }

    /**
     * 扩展 Helper 调用
     *
     * @param  string  $method
     * @param  array   $args
     * @return Helper
     * @throws Kohana_Exception
     */
    public function __call($method, array $args)
    {
        $class_name = 'Helper_'.$method;
        if ( ! class_exists($class_name))
        {
            throw new Kohana_Exception('Call to undefined method :class:::method',
                array(':class' => get_class($this), ':method' => $method));
        }

        $class = new ReflectionClass($class_name);

        return $class->newInstanceArgs($args);
    }

}